<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\Menu;
use common\models\Helper;

/**
 * Site controller
 */
class MenuController extends BaseController
{

    /**
     * 模块显示
     *
     * @author li
     * @since 2015-4-18
     */
    public function actionList()
    {
        $module = new Menu();
        $data = $module->moduleList();
        
        return $this->render('index', [
            'menu' => $data
        ]);
    }

    /**
     * 填加模块
     */
    public function actionAdd()
    {

        $menu = new Menu();
        if ($menu->load($post = Yii::$app->request->post())) {
            $menu->created_at = $menu->update_at = time();
            if ($menu->save()) {
                return $this->redirect('/menu/list');
            }
        }

        // var_dump($menu);die;
        $firstMenu = Menu::find()->where([
            'parent_id' => 0,
            'is_show' => 1,
            'channel' => 'admin'
        ])
            ->select('id,name')
            ->asArray()
            ->all();
        $t[0]['id'] = '0';
        $t[0]['name'] = '一级分类';

        $arr = array_merge($t, $firstMenu);
        return $this->render('add', [
            'model' => $menu,
            'menu' => $arr
        ]);
        
    }

    /**
     * 修改模块
     *
     * @author li
     * @since 2015-05-22
     *       
     */
    public function actionEdit()
    {
        $model = new Menu();
        $id = Yii::$app->request->get('id', 0);
        if ($id != 0) {
            $model = $model->findOne(['id' => $id]);
            //var_dump($model);die;
//            print_r(Yii::$app->request->post());die;
            if ($model->load(Yii::$app->request->post())) {
                if ($model->save()) {
                    return $this->redirect("/menu/list");
                }
            }
            return $this->render("edit", [
                'model' => $model,
                'id'    => $id
            ]);
        }
        return $this->redirect("/menu/list");
    }

    public function actionAjaxParentid()
    {
        $channel = Yii::$app->request->post('channel');
        $firstMenu = Menu::find()->where([
            'parent_id' => 0,
            'is_show' => 1,
            'channel' => "$channel"
        ])->asArray()->all();
        //var_dump($channel);die;
        $html = "<option value='0'>一级分类</option>";
        foreach($firstMenu as $v)
        {
            $html .= "<option value='". $v['id'] ."'>". $v['name'] ."</option>";
        }
        echo $html;
    }
}
